package com.itheima.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.core.domain.entity.SysUser;
import com.itheima.common.utils.DateUtils;
import com.itheima.common.utils.SecurityUtils;
import com.itheima.server.domain.Business;
import com.itheima.server.domain.Clue;
import com.itheima.server.domain.Transfer;
import com.itheima.server.dto.TransferQueryDto;
import com.itheima.server.service.ClueService;
import com.itheima.server.service.IBusinessService;
import com.itheima.server.service.TransferService;
import com.itheima.server.mapper.TransferMapper;
import com.itheima.system.service.ISysDictDataService;
import com.itheima.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.HashMap;

/**
* @author 蒋锐
* @description 针对表【hk_transfer】的数据库操作Service实现
* @createDate 2025-09-04 17:48:00
*/
@Service
@AllArgsConstructor
public class TransferServiceImpl extends ServiceImpl<TransferMapper, Transfer>
    implements TransferService {


    private final ClueService clueService;
    private final ISysDictDataService dictDataService;
    private final TransferMapper transferMapper;
    private final ISysUserService userService;
    private final IBusinessService businessService;


    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public Page<Transfer> pageQuery(TransferQueryDto dto) {
        Page<Transfer> transferPage = new Page<>();
        String userName = dto.getUserName();
        Integer userId = dto.getUserId();
        String phonenumber = dto.getPhonenumber();
        String beginTime = dto.getParams().get("beginTime");
        String endTime = dto.getParams().get("endTime");
        Page<Transfer> page = new Page<>();
        LambdaQueryWrapper<Transfer> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(userName),Transfer::getUserName, userName);
        wrapper.like(StringUtils.hasText(phonenumber),Transfer::getPhonenumber, phonenumber);
        wrapper.eq(userId!=null,Transfer::getUserId, userId);
        if (StringUtils.hasText(beginTime) && StringUtils.hasText(endTime)){
            try {
                DateUtils.parseDate(beginTime,"yyyy-MM-dd");
                DateUtils.parseDate(endTime,"yyyy-MM-dd");
                wrapper.between(Transfer::getCreateTime, beginTime, endTime);
            } catch (ParseException e) {
                 log.error("时间解析错误 {}",e);

            }
        }
        super.page(page,wrapper);
        return page;
    }

    @Override
    public void assignment(Integer type, Long outUserId, Long getUserId, HashMap<String, Object> map) {
        //查询被转派者对应数量的线索或商机数量
            int outNum = 0;
            int getNum = 0;
            if (type==0) {
                LambdaQueryWrapper<Clue> clueWrapper = new LambdaQueryWrapper<>();
                clueWrapper.eq(Clue::getOwner, outUserId);
                outNum = clueService.count(clueWrapper);
                clueWrapper.clear();
                clueWrapper.eq(Clue::getOwner, getUserId);
                getNum = clueService.count(clueWrapper);
            }else{
                LambdaQueryWrapper<Business> BusWrapper = new LambdaQueryWrapper<>();
                BusWrapper.eq(Business::getOwner, outUserId);
                outNum = businessService.count(BusWrapper);
                BusWrapper.clear();
                BusWrapper.eq(Business::getOwner, getUserId);
                getNum = businessService.count(BusWrapper);
            }
            //取出最大保有量
            Integer maxLimit = transferMapper.getMaxLimit(type == 0 ? 3 : 9);
            String typeName = type==0?"线索":"商机";
            if (outNum+getNum>maxLimit){
                map.put("msg",typeName+"转换失败！已经达到被转派人最大保有量");
                map.put("flag",false);
            }else{
                if (type==0){
                    //更改线索owner
                    UpdateWrapper<Clue> wrapper = new UpdateWrapper<>();
                    wrapper.eq("owner",getUserNameById(outUserId));
                    wrapper.set("owner",getUserNameById(getUserId));
                    wrapper.set("transfer",getUserNameById(SecurityUtils.getUserId()));
                    clueService.update(wrapper);
                }else{
                    //更改商机owner
                    UpdateWrapper<Business> wrapper = new UpdateWrapper<>();
                    wrapper.clear();
                    wrapper.eq("owner",getUserNameById(outUserId));
                    wrapper.set("owner",getUserNameById(getUserId));
                    businessService.update(wrapper);
                }
                map.put("msg",typeName+"转换成功！,已经分配"+outNum+typeName);
                map.put("flag",true);
            }
    }

    private String getUserNameById(Long userId){
        SysUser sysUser = userService.selectUserById(userId);
        return sysUser.getUserName();
    }


}




